import re
import json
import requests
from urllib.parse import unquote

class DOUYIN():
    def getInfos(self, params):
        rid = params['rid']
        url = "https://live.douyin.com/" + rid
        header = {
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
            "upgrade-insecure-requests": "1",
        }
        session = requests.session()
        r = session.get(url, headers=header, timeout=15)
        cookie = re.search(r'(?i)__ac_nonce=(.*?);', r.headers["Set-Cookie"]).group(1)
        cookie = requests.cookies.create_cookie("__ac_nonce", cookie)
        session.cookies.set_cookie(cookie)
        r = session.get(url, headers=header, timeout=15)
        hlsStr = re.search(r'"hls_pull_url_map\\":({.*?}),\\"', r.text).group(1).replace('\\', '')
        mediaMap = json.loads(hlsStr)
        urlDict = {}
        for ratio in mediaMap:
            if ratio == 'FULL_HD1':
                urlDict.update({0: mediaMap[ratio]})
            elif ratio == 'HD1':
                urlDict.update({1: mediaMap[ratio]})
            elif ratio == 'SD1':
                urlDict.update({2: mediaMap[ratio]})
            else:
                urlDict.update({3: mediaMap[ratio]})
            key = sorted(urlDict)[0]
            url = urlDict[key]
        return url
